package com.dsjy.yf.address.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsjy.yf.address.config.base.BizException;
import com.dsjy.yf.address.config.base.CommonEnum;
import com.dsjy.yf.address.entity.dataobject.PoiDO;
import com.dsjy.yf.address.entity.myenum.OperateEnum;
import com.dsjy.yf.address.mapper.PoiMapper;
import com.dsjy.yf.address.service.PoiService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

/**
 * @author whj
 * @version 1.0
 * @date 2021-03-02 9:05
 */
@Service
public class PoiServiceImpl implements PoiService {

    @Resource
    private PoiMapper poiMapper;

    @Override
    @Cacheable(value = "poi", key = "'searchPoiWithParentCode'+#parentCode+#flag")
    public List<PoiDO> searchPoiWithParentCode(Integer parentCode, Boolean flag) {
        return poiMapper.searchPoiWithParentCode(parentCode, flag);
    }

    @Override
    @Caching(evict = {
            @CacheEvict(value = "poi", condition = "#poiDO.parentCode != null",
                    key = "'searchPoiWithParentCode'+#poiDO.parentCode+'false'"),
            @CacheEvict(value = "poi", condition = "#poiDO.parentCode != null",
                    key = "'searchPoiWithParentCode'+#poiDO.parentCode+'true'")
    })
    @Transactional(rollbackFor = RuntimeException.class)
    public Integer addUpdDel(String operate, PoiDO poiDO) {
        Integer result = null;
        if (OperateEnum.ADD.getOperate().equals(operate) && poiDO.getPoiName() != null) {
            result = addPoi(poiDO);
        } else if (OperateEnum.UPDATE.getOperate().equals(operate) && poiDO.getId() != null) {
            result = updPoi(poiDO);
        }
        return result;
    }

    @Override
    public Integer addPoi(PoiDO poiDO) {
        if (poiDO.getParentCode() == null || String.valueOf(poiDO.getParentCode()).length() != 6) {
            throw new BizException(CommonEnum.PARAM_ERROR);
        }
        poiDO.setCreateTime(new Timestamp(System.currentTimeMillis()));
        return poiMapper.addPoi(poiDO);
    }


    @Override
    public Integer updPoi(PoiDO poiDO) {
        poiDO.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        return poiMapper.updPoi(poiDO);
    }

    @Override
    public IPage searchWithPage(Integer pageNum, Integer pageSize, QueryWrapper wrapper) {
        wrapper.setEntityClass(PoiDO.class);
        Page<PoiDO> page = new Page<>(pageNum, pageSize);
        return poiMapper.selectPage(page, wrapper);
    }
}
